<?php


namespace App\Models\CacheModel\live;


use App\Models\Api\BaseCache;

class LiveCouponActiveGiveRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_coupon_active_give_record';

    /**
     * 更新优惠券活动领取优惠券记录
     * @param int $user_cid zl_user_coupon表的ID
     * @param array $data
     * @return bool
     */
    public function updateData($user_cid, $data)
    {
        try
        {
            $this->where(['user_cid' => $user_cid])->update($data);
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 获取当前优惠券活动使用概率
     */
    public function getCouponActiveUseRatio($id)
    {
        $res = $this->where('coupon_active', $id)->column('use_coupon_time');

        if (empty($res))
        {
            return '0.0';
        }

        $allNum = count($res);

        $userNum = count(array_filter($res));

        return sprintf("%.1f", ($userNum / $allNum) * 100);
    }

    /**
     * 获取本次直播记录优惠券使用概率
     */
    public function getLiveRecordCouponUseRatio($liveRecordId, $useMaxTime = null)
    {
        $res = $this->where('live_record_id', $liveRecordId)->column('use_coupon_time');

        if (empty($res))
        {
            return '0.0';
        }

        $allNum = count($res);

        $userData = array_filter($res, function ($val) use ($useMaxTime)
        {
            if (!is_null($useMaxTime))
            {
                if ($val > 0 && $val <= $useMaxTime)
                {
                    return true;
                } else
                {
                    return false;
                }
            } else
            {
                if ($val > 0)
                {
                    return true;
                } else
                {
                    return false;
                }
            }
        });

        return sprintf("%.1f", (count($userData) / $allNum) * 100);
    }
}

